package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.service.ReportService;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 统计报表
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员折线图
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
//        Map<String,Object> map=new HashMap<>();
        // 组装过去12个月的数据, 前端是一个数组
        List<String> months = new ArrayList<String>();
        // 使用java中的calendar来操作日期, 日历对象
        Calendar calendar = Calendar.getInstance();
        // 设置过去一年的时间  年-月-日 时:分:秒, 减去12个月
        calendar.add(Calendar.YEAR, -1);
        // 构建12个月的数据
        for (int i = 0; i < 12; i++) {
            try{
                // 每次增加一个月就
                calendar.add(Calendar.MONTH, 1);
                // 过去的日期, 设置好的日期
                Date date = calendar.getTime();
                // 转换成我们数据库可以使用的'yyyy-MM-dd'字符串
                String dateString = DateUtils.parseDate2String(date);
                //添加组拼好的过去12个月的月份到List集合
                months.add(dateString);
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        // 调用服务查询过去12个月会员数据 前端也是一数组 数值
        List<Integer> memberCount =memberService.getMemberReport(months);
        // 放入map
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("months",months);
        resultMap.put("memberCount",memberCount);

        // 再返回给前端
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,resultMap);
    }

//    套餐饼形图
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        List<Map<String, Object>> list = setmealService.getSetmalReport();
        Map<String,Object> map=new HashMap<>();
        map.put("setmealCount",list);
        List<String> setmealNames=new ArrayList<>();
        for (Map<String,Object> m:list){
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames",setmealNames);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    /**
     * 运营统计数据
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        Map<String, Object> businessReport = reportService.getBusinessReportData();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,businessReport);
    }


    /**
     * 导出运营统计数据报表
     * 1.获取到这个表的所有数据（已完成）
     * 2.读取Excel模板
     * 3.将数据写入到Excel
     * 4.导出，使用IO流将Excel下载
     */
    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String,Object> result=reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate"); //当前时间
            Integer todayNewMember = (Integer) result.get("todayNewMember"); //今日新增会员数
            Integer totalMember = (Integer) result.get("totalMember"); //总会员数
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember"); //本周新增会员数
            Integer thisMonthNewMember= (Integer) result.get("thisMonthNewMember"); //本月新增会员数
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber"); //今日预约数
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber"); //今日到诊数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber"); //本周预约数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber"); //本周到诊数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber"); //本月预约数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber"); //本月到诊数
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal"); //热门套餐

            String filePath = request.getSession().getServletContext()
                    .getRealPath("template")+ File.separator+"report_template.xlsx";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);//从零开始读取第三行
            row.getCell(5).setCellValue(reportDate);//从零开始读取第六列,写入上面取得的日期

            row = sheet.getRow(4);//从零开始读取第五行
            row.getCell(5).setCellValue(todayNewMember);//从零开始读取第六列,写入上面取得的新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//从零开始读取第八列,写入上面取得的总会员数

            row=sheet.getRow(5);//从零开始读取第六行
            row.getCell(5).setCellValue(thisWeekNewMember);//从零开始读取第六列,写入上面取得的本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//从零开始读取第八列,写入上面取得的//本月新增会员数

            row=sheet.getRow(7);//从零开始读取第八行
            row.getCell(5).setCellValue(todayOrderNumber);//从零开始读取第六列,写入上面取得的今日预约数
            row.getCell(7).setCellValue(thisWeekOrderNumber);//从零开始读取第八列,写入上面取得的今日到诊数

            row=sheet.getRow(8);//从零开始读取第九行
            row.getCell(5).setCellValue(thisMonthOrderNumber);//从零开始读取第六列,写入上面取得的本周预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//从零开始读取第八列,写入上面取得的本周到诊数

            row=sheet.getRow(9);//从零开始读取第十行
            row.getCell(5).setCellValue(thisWeekVisitsNumber);//从零开始读取第六列,写入上面取得的本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//从零开始读取第八列,写入上面取得的本月到诊数

            int rowNum = 12;
            for (Map map:hotSetmeal){
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                String remark=(String) map.get("remark");

                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
                row.getCell(7).setCellValue(remark);//备注
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
















}